package com.soulapp.hook.hooker

import com.highcapable.kavaref.KavaRef.Companion.resolve
import com.highcapable.kavaref.condition.type.Modifiers
import com.highcapable.yukihookapi.hook.core.YukiMemberHookCreator.MemberHookCreator.Result
import com.highcapable.yukihookapi.hook.log.YLog
import com.soulapp.data.ConfigData

// 解除截图限制
object LimitCaptureHook : BaseHooker() {
    private const val TAG = "LimitCaptureHook"
    private var windowHook: Result? = null
    private var surfaceViewHook: Result? = null

    override fun getKey() = ConfigData.limitCapture

    override fun onHook() {
        startHook()
    }

    override fun startHook() {
        YLog.debug("startHook $TAG $hookEnabled")
        if (!hookEnabled) return

        windowHook = "android.view.Window".toClass()
            .resolve()
            .optional()
            .method {
                modifiers(Modifiers.PUBLIC)
                name("setFlags")
                parameters(Int::class.java, Int::class.java)
                returnType = Void::class.javaPrimitiveType
            }
            .first()
            .hook {
                before {
                    val flags = args[0] as? Int ?: return@before
                    args[0] = flags and (-8193)
                }
            }

        surfaceViewHook = "android.view.SurfaceView".toClass()
            .resolve()
            .optional()
            .method {
                modifiers(Modifiers.PUBLIC)
                name("setSecure")
                parameters(Boolean::class.java)
                returnType = Void::class.javaPrimitiveType
            }
            .first()
            .hook {
                before {
                    args(0).setFalse()
                }
            }
    }

    override fun stopHook() {
        if (hookEnabled) return
        windowHook?.let {
            it.remove {
                YLog.debug("stopHook windowHook $TAG 成功")
            }
        } ?: YLog.debug("stopHook windowHook $TAG 失败")

        surfaceViewHook?.let {
            it.remove {
                YLog.debug("stopHook surfaceViewHook $TAG 成功")
            }
        } ?: YLog.debug("stopHook surfaceViewHook $TAG 失败")

    }

}